package com.gopay.scheduler.service.jobmonitor.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.quartz.CronTrigger;
import org.quartz.JobExecutionContext;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.impl.StdScheduler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Service;

import com.gopay.common.util.DateUtils;
import com.gopay.remote.cron.JobMonitorQueryRemoteService;
import com.gopay.remote.cron.vo.JobMonitorQueryRes;

/**
 * @JobMonitorQueryServiceImpl.java
 * @author fanghw
 * @2015年5月15日 下午2:14:26 www.gopay.com.cn Inc.All rights reserved.
 */
public class JobMonitorQueryServiceImpl implements JobMonitorQueryRemoteService {
   
	private static final long serialVersionUID = -2489922173822144264L;

	// 日志
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private StdScheduler schFactoryBean;

    /**
     * 统计全部Job信息
     * 
     * @return
     */
    public String[] statAllJobInfo() {
 /*       try {
            String[] triggerNames = schFactoryBean.getTriggerNames(null);
//            String msgTitle="计划中的任务总共有" + triggerNames.length + "个";
            String stat = schFactoryBean.isStarted() ? " 开启 状态" : (schFactoryBean.isShutdown() ? " 关闭 状态" : (schFactoryBean.isInStandbyMode() ? "StandbyMode" : " 异常 状态"));
            String msgTitle=String.format("scheduler处于%s，共包含任务%s个", stat, triggerNames.length);
            StringBuilder sb = new StringBuilder();
            int errCount = 0, noneCount = 0, normalCount = 0, pausedCount = 0, completeCount = 0, blockCount = 0;

            for (String name : triggerNames) {
                switch (schFactoryBean.getTriggerState(name, null)) {
                case Trigger.STATE_NONE:
                    noneCount++;
                    break;
                case Trigger.STATE_NORMAL:
                    normalCount++;
                    break;
                case Trigger.STATE_PAUSED:
                    pausedCount++;
                    break;
                case Trigger.STATE_COMPLETE:
                    completeCount++;
                    break;
                case Trigger.STATE_BLOCKED:
                    blockCount++;
                    break;
                case Trigger.STATE_ERROR:
                    errCount++;
                    break;
                default:
                    break;
                }
            }

            int count = 1;
            if (normalCount > 0) {
                sb.append(count++).append(". 正常任务" + normalCount + "个\r\n");
            }
            if (errCount > 0) {
                sb.append(count++).append(". 错误任务" + errCount + "个\r\n");
            }
            if (pausedCount > 0) {
                sb.append(count++).append(". 暂停任务" + pausedCount + "个\r\n");
            }
            if (blockCount > 0) {
                sb.append(count++).append(". 阻塞任务" + blockCount + "个\r\n");
            }
            if (completeCount > 0) {
                sb.append(count++).append(". 完成任务" + completeCount + "个\r\n");
            }
            if (noneCount > 0) {
                sb.append(count++).append(". 删除任务" + noneCount + "个\r\n");
            }

            return new String[]{msgTitle,sb.toString()};
re
        } catch (SchedulerException e) {
            logger.error("任务监控Job异常", e);
            return null;
        }*/
    	return null;
    }

    /**
     * 统计正在运行Job信息
     * 
     * @return
     */
    public String[] statRunningJobInfo() {        
       /* List<JobExecutionContext> jobList = schFactoryBean.getCurrentlyExecutingJobs();
        String msgTitle="运行中的任务有" + jobList.size() + "个";
        StringBuilder sb = new StringBuilder();

        int count = 1;
        for (JobExecutionContext executingJob : jobList) {
            Trigger trigger = executingJob.getTrigger();
            sb.append(count++).append(". ");
            sb.append(trigger.getName().substring(0, trigger.getName().indexOf("Trigger"))).append("\r\n");
        }

        return new String[]{msgTitle,sb.toString()};*/
    	
    	return null;
    }
    
    public List<JobMonitorQueryRes> query(String type) {
        List<JobMonitorQueryRes> rsList = null;
        try {

            List<Trigger> triggerList;
            if ("all".equals(type)) {
                triggerList = getAllTrigger();
            } else {
                triggerList = getRunningTrigger();
            }
            rsList = buildJobResult(triggerList);

        } catch (Exception e) {
            logger.error("job监控查询异常", e);
        }

        return rsList;
    }

    private List<Trigger> getAllTrigger() throws SchedulerException {
        List<Trigger> trList = new ArrayList<Trigger>();
/*
        String[] triggerNames = schFactoryBean.getTriggerNames(null);
        for (String name : triggerNames) {
            Trigger trigger = schFactoryBean.getTrigger(name, null);
            trList.add(trigger);
        }
*/
        return trList;
    }

    private List<Trigger> getRunningTrigger() {
        List<Trigger> trList = new ArrayList<Trigger>();

        List<JobExecutionContext> jobList = schFactoryBean.getCurrentlyExecutingJobs();
        for (JobExecutionContext executingJob : jobList) {
            Trigger trigger = executingJob.getTrigger();
            trList.add(trigger);
        }

        return trList;
    }

    private List<JobMonitorQueryRes> buildJobResult(List<Trigger> triggerList) throws SchedulerException {
        List<JobMonitorQueryRes> rsList = new ArrayList<JobMonitorQueryRes>();
       /* JobMonitorQueryRes r;
        for (Trigger trigger : triggerList) {
            r = new JobMonitorQueryRes();
            r.setTriggerName(trigger.getName().substring(0, trigger.getName().indexOf("Trigger")));
            if (trigger instanceof CronTrigger) {
                CronTrigger cronTrigger = (CronTrigger) trigger;
                r.setCronExpression(cronTrigger.getCronExpression());
            }
            r.setTriggerState(translateTriggerState(schFactoryBean.getTriggerState(trigger.getName(), null)));
            r.setPreviousFireTime(trigger.getPreviousFireTime() == null ? "" : DateUtils.format(
                    trigger.getPreviousFireTime(), "yyyy-MM-dd HH:mm:ss"));
            r.setNextFireTime(trigger.getNextFireTime() == null ? "" : DateUtils.format(trigger.getNextFireTime(),
                    "yyyy-MM-dd HH:mm:ss"));

            rsList.add(r);
        }
*/
        return rsList;
    }

    private String translateTriggerState(int state) {
        String name = "";
      /*  switch (state) {
        case Trigger.STATE_NONE:
            name = "删除";
            break;
        case Trigger.STATE_NORMAL:
            name = "正常";
            break;
        case Trigger.STATE_PAUSED:
            name = "暂停";
            break;
        case Trigger.STATE_COMPLETE:
            name = "完成";
            break;
        case Trigger.STATE_BLOCKED:
            name = "阻塞";
            break;
        case Trigger.STATE_ERROR:
            name = "错误";
            break;
        default:
            break;
        }
*/
        return name;
    }
}
